﻿package pl.kozulowski.loaders {
	
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.system.SecurityDomain;
	
	public class SimpleLoader extends Loader {
		
		private var _url:String;
		private var _req:URLRequest;
		private var _bytesl:Number = 0;
		private var _bytest:Number = 0;
		private var _context:LoaderContext;
		
		public function SimpleLoader() {
			super();
		}
		
		public function loadFile($url:String):void {		// Loads a file specified by the $url parameter
			//_context = new LoaderContext();
			//_context.securityDomain = SecurityDomain.currentDomain;
			_req = new URLRequest($url);
			super.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
			super.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
			super.load(_req);
		}
		
		private function onProgress($e:ProgressEvent):void {
			_bytesl = $e.bytesLoaded;
			_bytest = $e.bytesTotal;
			dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS));
		}
		
		private function onLoaded($e:Event):void {
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		override public function get content():DisplayObject {		// returns loaded content
			return super.content;
		}
		
		public function get displayObject():DisplayObject {
			return super;
		}
		
		public function stop():void {
			super.close();
		}
		
		public function get bytesLoaded():Number {		// returns loaded bytes
			return _bytesl;
		}
		
		public function get bytesTotal():Number {		// returns total bytes
			return _bytest;
		}
		
		public function get progress():Number {		// returns loading progress
			return _bytesl/_bytest;
		}
		
		public function get percentageProgress():String {		//returns loading progress represented in percentage
			return String(Math.round((_bytesl/_bytest)*100) + '%');
		}
	}
}